package com.example.schedule.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.AlarmClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.schedule.R;
import com.example.schedule.db.Plan;
import com.example.schedule.utils.DoubleClick;

import org.litepal.LitePal;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.schedule.MainActivity.count;
import static com.example.schedule.today.NoteActivity.sTodayPlanAdapter;

public class TodayPlanAdapter extends RecyclerView.Adapter<TodayPlanAdapter.MyHolder> {
    private Context mContext;
    List<Plan> mDataList = null;
    private int mIndex = 0;
    private String TAG = "yesen";
    private static int imagePosition;

    public TodayPlanAdapter(List<Plan> planTextList) {
        mDataList = planTextList;
    }

    public class MyHolder extends RecyclerView.ViewHolder {

        private final TextView mItemTodayText;
        private final ImageView mItemTodayFinish;
        private final Button mItemTodayDelete;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            mItemTodayText = itemView.findViewById(R.id.item_today_tv);
            mItemTodayFinish = itemView.findViewById(R.id.item_today_finish);
            mItemTodayDelete = itemView.findViewById(R.id.item_today_delete);
        }
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_plan , parent , false);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        mIndex = position;
        Plan plan = mDataList.get(position);
        holder.mItemTodayText.setText(plan.getWritePlan());

        final Handler handler = new Handler(Looper.myLooper()) {  //异步消息处理机制来在非主线程中来修改UI

            public void handleMessage(Message msg){
                switch (msg.what){
                    case 1:
                        mDataList.remove(imagePosition);  //将该Plan从列表中移除（此时数据库中的没有移除）
                        sTodayPlanAdapter.notifyDataSetChanged();  //更新适配器以达到更新列表的效果
                        holder.mItemTodayFinish.setImageResource(R.drawable.no);  //将前面的框框换回成灰色
                        break;
                    default:
                        break;
                }
            }
        };

        holder.mItemTodayFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imagePosition = holder.getAdapterPosition();
                Plan ImagePlan = mDataList.get(imagePosition);
                holder.mItemTodayFinish.setImageResource(R.drawable.yes);  //切换图片
                ImagePlan.setStatus(true);  //状态设置为完成
                ImagePlan.save();  //保存该状态
                count--;  //移除之后数量减1
                Plan finishPlan = mDataList.get(imagePosition);
                String finishWrite = finishPlan.getWritePlan();
                TimerTask task1 = new TimerTask() {  //设置定时任务
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);  //发送异步Message
                    }
                };
                Timer timer = new Timer();
                timer.schedule(task1, 800);  //设置延时的时间，单位是毫秒
                Animation animation = AnimationUtils.loadAnimation(v.getContext(),R.anim.today_anim);  //设置动画
                holder.mItemTodayFinish.startAnimation(animation);
                holder.mItemTodayText.startAnimation(animation);
                deleteFromDB(finishWrite);
            }
        });

        holder.mItemTodayDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int deletePosition = holder.getAdapterPosition();  //得到点击的顺序
                //Log.d(TAG, "onClick: " +deletePosition +"-------"+position);
                Plan deletePlan = mDataList.get(deletePosition);
                String deletePlanWrite = deletePlan.getWritePlan();
                mDataList.remove(deletePosition);
                count--;  //数量减少
                sTodayPlanAdapter.notifyDataSetChanged();  //更新适配器
                TimerTask deleteTask = new TimerTask() {
                    @Override
                    public void run() {
                        holder.mItemTodayDelete.setVisibility(View.INVISIBLE);
                    }
                };
                Timer deleteTimer = new Timer();
                deleteTimer.schedule(deleteTask,0);
                deleteFromDB(deletePlanWrite);
            }
        });

        holder.mItemTodayText.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
               // Toast.makeText(mContext, "长按了~", Toast.LENGTH_SHORT).show();
                holder.mItemTodayDelete.setVisibility(View.VISIBLE);
                return true;
            }
        });

        holder.mItemTodayText.setOnClickListener(new DoubleClick() {
            @Override
            public void doubleC(View view) {
                //跳转系统闹钟
                Intent alarmas = new Intent(AlarmClock.ACTION_SET_ALARM);
                view.getContext().startActivity(alarmas);
            }
        });
    }

    private void deleteFromDB(String key) {
        LitePal.deleteAll(Plan.class , "writePlan = ?",key);
    }

    public void refreshData(List<Plan> planList){
        mDataList = planList;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

}
